<template>
<div :class="['modal', {fade: fade}]" data-backdrop="static" data-disable="false" data-keyboard="true" tabindex="-1">
  <div :class="['modal-dialog', size]">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title text-center text-primary"><span>{{title}}</span></h4>
      </div>
      <div class="modal-body">
        <div class="form-inline" autocomplete="off" spellcheck="false">
            <div class="form-group form-group-sm">
                <label>搜索</label>
                <input type="text" class="form-control" placeholder="关键字" v-model.trim="q" @keydown.enter.prevent ref="q">
            </div>
        </div>
        <br>
        <el-table :data="channels" stripe @sort-change="sortChange" :max-height="500" @row-click="rowClick" :row-style="rowStyle"
            ref="channelTable" v-loading="loading" element-loading-text="加载中...">
            <el-table-column prop="Channel" label="通道号" min-width="90" show-overflow-tooltip sortable="custom" :fixed="!isMobile()"></el-table-column>
            <el-table-column prop="Name" label="通道名称" min-width="150" :formatter="formatName" show-overflow-tooltip></el-table-column>
            <el-table-column min-width="200" label="通道快照">
                <template slot-scope="props">
                    <img onerror="this.src='/images/default_snap.png';" style="height:30px;width:50px;" :src="props.row.SnapURL" v-if="isMobile()">
                    <el-popover placement="left" :title="`[${props.row.Channel}] ${props.row.Name}`" width="300" trigger="hover" v-else>
                        <img onerror="this.src='/images/default_snap.png';" style="width:100%;height:100%;" :src="props.row.SnapURL">
                        <img onerror="this.src='/images/default_snap.png';" style="height:30px;width:50px;" slot="reference" :src="props.row.SnapURL">
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column prop="Online" label="在线状态" min-width="90">
                <template slot-scope="props">
                <span v-if="props.row.Online == 1" class="text-primary">在线</span>
                <span v-else>离线</span>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-if="total > 0" layout="total,prev,pager,next" :pager-count="isMobile() ? 3 : 5" class="pull-right" :total="total" :page-size.sync="pageSize" :current-page.sync="currentPage"></el-pagination>
        <div class="clearfix"></div>
      </div>
      <!-- <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
      </div> -->
    </div>
    <!-- /.modal-content -->
  </div>
  <!-- /.modal-dialog -->
</div>
</template>

<script>
import _ from 'lodash'
import $ from 'jquery'
import "jquery-ui/ui/widgets/draggable";

export default {
  props: {
      title: {
          default: ''
      },
      token: {
          default: ''
      },
      size: {
          type: String,
          default: 'modal-lg'
      },
      fade: {
          type: Boolean,
          default: false
      }
  },
  data() {
    return {
      q: "",
      total: 0,
      pageSize: 10,
      currentPage: 1,
      sort: "",
      order: "",
      loading: false,
      channels: [],
      index: 0,
    };
  },
  watch: {
    q: function(newVal, oldVal) {
        this.doDelaySearch();
    },
    currentPage: function(newVal, oldVal) {
        this.doSearch(newVal);
    },
    pageSize: function(newVal, oldVal) {
        this.doSearch();
    }
  },
  mounted() {
    $(this.$el).find('.modal-content').draggable({
        handle: '.modal-header',
        cancel: ".modal-title span",
        addClasses: false,
        containment: 'document',
        delay: 100,
        opacity: 0.5
    });
    $(this.$el).on("shown.bs.modal", () => {
        this.$emit("show");
    }).on("hidden.bs.modal", () => {
        this.errors.clear();
        // this.reset();
        this.$emit("hide");
    })
  },
  methods: {
    sortChange(data) {
      this.sort = data.prop;
      this.order = data.order == "ascending" ? "asc" : "desc";
      this.getChannels();
    },
    doSearch(page = 1) {
        this.currentPage = page;
        this.getChannels();
    },
    doDelaySearch: _.debounce(function() {
        this.doSearch();
    }, 500),
    formatName(row, col, cell) {
      return row.CustomName || row.Name || "-";
    },
    formatManufacturer(row, col, cell) {
      if (cell) return cell;
      return "-";
    },
    getChannels() {
        this.loading = true;
        var param = {
            q: this.q,
            online: true,
            start: (this.currentPage -1) * this.pageSize,
            limit: this.pageSize,
            sort: this.sort,
            order: this.order
        }
        if (this.token) {
          param.token = this.token;
        }
        $.get("/api/v1/getchannels", param).then(ret => {
            this.total = (ret.LiveQing || ret.NVR).Body.ChannelCount || 0;
            this.channels = (ret.LiveQing || ret.NVR).Body.Channels || [];
        }).always(() => {
            this.$nextTick(() => {
              this.loading = false;
            })
        });
    },
    rowClick(row, event, column) {
      if(row.Online != 1) return;
      this.$emit("selected", this.index, row);
      this.hide();
    },
    rowStyle({row, rowIndex}) {
      if(row.Online == 1) {
        return "cursor:pointer";
      }
      return "";
    },
    reset() {
      this.index = 0;
      this.channels = [];
      this.q = "";
      this.currentPage = 1;
      this.pageSize = 10;
    },
    show(index) {
      this.index = index;
      $(this.$el).modal("show");
      this.getChannels();
    },
    hide() {
      $(this.$el).modal("hide");
    },
  }
};
</script>
